//
//  MTGiftController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/9.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import RxSwift
import RxCocoa
import Moya
import Result

class MTGiftController: BaseViewController {
    
    /// MineApi
    private lazy var provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    
    ///UserCenterApi
    private lazy var user_provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    
    private let disposeBag = DisposeBag()
    
    var model: MineAccountModel? {
        didSet {
            guard let model = model else { return }
            amountLabel.text = "\(model.receiveGiftAmount + model.receiveRedPacketAmount)"
            dimondValueLab.text = "\(model.translateAmount)钻"
            withdrawValueLab.text = "\(model.withdrawMoney)元"
            moneyArr.append(model.receiveGiftAmount)
            moneyArr.append(model.receiveRedPacketAmount)
            tableView.reloadData()
        }
    }
    
    lazy var moneyArr: [Int] = {
        return []
    }()
    
    lazy var exchangeArr: [MineWithdrawModel] = {
        return []
    }()
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(AccountListCell.self, forCellReuseIdentifier: AccountListCell.reuseIdentity())
        table.separatorInset = UIEdgeInsets.zero
        table.tableFooterView = UIView()
        return table
    }()
    
    lazy var headerBack: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex:0xf6f6f6)
        return view
    }()
    
    lazy var blackBack: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex:0x2f2f2f)
        return view
    }()
    
    lazy var titleLab: UILabel = {
        let lab = UILabel()
        lab.text = "累计获得礼物"
        lab.font = PingFangSCMediumFont(12)
        lab.textColor = UIColor(hex:0x9b9b9b)
        lab.textAlignment = .center
        return lab
    }()
    
    lazy var icon: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "club_gift")
        return imageView
    }()
    
    lazy var amountLabel: UILabel = {
        let l = UILabel()
        l.textColor = .white
        l.font = PingFangSCSemiboldFont(20)
        l.textAlignment = .right
        return l
    }()
    
    lazy var subView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 8
        return view
    }()
    
    lazy var dimondTitleLab: UILabel = {
        let lab = UILabel()
        lab.text = "累计可兑换钻石"
        lab.font = PingFangSCMediumFont(10)
        lab.textColor = UIColor(hex:0x9b9b9b)
        lab.textAlignment = .center
        return lab
    }()
    
    lazy var dimondValueLab: UILabel = {
        let lab = UILabel()
        lab.font = PingFangSCSemiboldFont(14)
        lab.textColor = UIColor(hex:0x1d1a1a)
        lab.textAlignment = .center
        return lab
    }()
    
    lazy var dimondBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("兑换钻石", for: .normal)
        btn.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        btn.backgroundColor = UIColor(hex:0xffc000)
        btn.layer.cornerRadius = 12
        btn.titleLabel?.font = PingFangSCSemiboldFont(12)
        btn.addTarget(self, action: #selector(giftController(didClickExchangeButton:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex:0xe6e6e6)
        return view
    }()
    
    lazy var withdrawTitleLab: UILabel = {
        let lab = UILabel()
        lab.text = "累计可提现"
        lab.font = PingFangSCMediumFont(10)
        lab.textColor = UIColor(hex:0x9b9b9b)
        lab.textAlignment = .center
        return lab
    }()
    
    lazy var withdrawValueLab: UILabel = {
        let lab = UILabel()
        lab.font = PingFangSCSemiboldFont(14)
        lab.textColor = UIColor(hex:0x1d1a1a)
        lab.textAlignment = .center
        return lab
    }()
    
    lazy var withdrawBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("提现", for: .normal)
        btn.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        btn.backgroundColor = UIColor(hex:0xffc000)
        btn.layer.cornerRadius = 12
        btn.titleLabel?.font = PingFangSCSemiboldFont(12)
        btn.addTarget(self, action: #selector(giftController(didClickWithdrawButton:)), for: .touchUpInside)
        return btn
    }()
    
    private func loadData() {
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        queryReceiveStatics()
        translateTickets()
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        title = "我的礼物"
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 56, height: 20))
        button.setTitle("联系客服", for: .normal)
        button.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        button.titleLabel?.font = PingFangSCMediumFont(14)
        button.addTarget(self, action: #selector(giftController(didClickContactButton:)), for: .touchUpInside)
        let rightBarButton = UIBarButtonItem(customView: button)
        self.navigationItem.rightBarButtonItem = rightBarButton
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
}

extension MTGiftController {
    private func headerView() -> UIView {
        headerBack.addSubview(blackBack)
        blackBack.addSubview(titleLab)
        blackBack.addSubview(icon)
        blackBack.addSubview(amountLabel)
        headerBack.addSubview(subView)
        subView.addSubview(dimondTitleLab)
        subView.addSubview(dimondValueLab)
        subView.addSubview(dimondBtn)
        subView.addSubview(lineView)
        subView.addSubview(withdrawTitleLab)
        subView.addSubview(withdrawValueLab)
        subView.addSubview(withdrawBtn)
        
        blackBack.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(0)
            make.height.equalTo(120)
        }
        
        titleLab.snp.makeConstraints { (make) in
            make.centerX.equalTo(blackBack)
            make.top.equalTo(20)
        }
        
        amountLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(titleLab).offset(-8)
            make.top.equalTo(titleLab.snp.bottom).offset(3)
        }
        
        icon.snp.makeConstraints { (make) in
            make.left.equalTo(amountLabel.snp.right).offset(4)
            make.centerY.equalTo(amountLabel)
            make.width.height.equalTo(24)
        }
        
        subView.snp.makeConstraints { (make) in
            make.top.equalTo(headerBack).offset(80)
            make.left.equalTo(headerBack).offset(17)
            make.right.equalTo(headerBack).offset(-17)
            make.height.equalTo(80)
        }
        
        dimondTitleLab.snp.makeConstraints { (make) in
            make.top.equalTo(subView).offset(7)
            make.width.equalTo((ScreenWidth-34) / 2)
        }
        
        dimondValueLab.snp.makeConstraints { (make) in
            make.top.equalTo(dimondTitleLab.snp.bottom).offset(3)
            make.width.equalTo((ScreenWidth-34) / 2)
        }
        
        dimondBtn.snp.makeConstraints { (make) in
            make.top.equalTo(dimondValueLab.snp.bottom).offset(4)
            make.centerX.equalTo(dimondTitleLab)
            make.width.equalTo(64)
            make.height.equalTo(24)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.centerY.centerX.equalTo(subView)
            make.width.equalTo(2)
            make.height.equalTo(63)
        }
        
        withdrawTitleLab.snp.makeConstraints { (make) in
            make.top.equalTo(subView).offset(7)
            make.left.equalTo(lineView.snp.right)
            make.width.equalTo((ScreenWidth-34) / 2)
        }
        
        withdrawValueLab.snp.makeConstraints { (make) in
            make.top.equalTo(withdrawTitleLab.snp.bottom).offset(3)
            make.left.equalTo(lineView.snp.right)
            make.width.equalTo((ScreenWidth-34) / 2)
        }
        
        withdrawBtn.snp.makeConstraints { (make) in
            make.top.equalTo(withdrawValueLab.snp.bottom).offset(4)
            make.centerX.equalTo(withdrawTitleLab)
            make.width.equalTo(64)
            make.height.equalTo(24)
        }
        
        return headerBack
    }
}

extension MTGiftController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

extension MTGiftController {
    private func queryReceiveStatics() {
        provider.rx.requestResult(.receiveStatics).subscribe(onNext: { [weak self] (result: Result<MineAccountResponseModel, AnyError>, isCache: Bool) in
            
            guard let weakSelf = self else {
                return
            }
            switch result {
            case let .success(response):
                
                if let code = response.code, code == 200 {
                    if let result = response.result {
                        weakSelf.model = result
                    }
                } else {
                    if let msg = response.message {
                        AlertManager.presentAlertView(message: msg)
                    }
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }).disposed(by: globalDisposedBag)
    }
    
    private func translateTickets() {
        user_provider.rx.requestResult(.translateTicket).subscribe(onNext: { [weak self] (result: Result<MineWithdrawResponseModel, AnyError>, isCache: Bool) in
            
            guard let weakSelf = self else {
                return
            }
            switch result {
            case let .success(response):
                
                if let code = response.code, code == 200 {
                    if let resultT = response.resultT {
                        weakSelf.exchangeArr = resultT
                    }
                } else {
                    if let msg = response.message {
                        AlertManager.presentAlertView(message: msg)
                    }
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }).disposed(by: globalDisposedBag)
    }
}


// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTGiftController {
    
    private func giftController(didClickContactButton sender: UIButton) {
        if let un = UserCenter.default.customerUserName {
            JMSGConversation.createSingleConversation(withUsername: un) { [weak self] (conversation, error) in
                guard let weakSelf = self else { return }
                if error == nil, conversation != nil {
                    if let nav = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.viewControllers?[1] as? BaseNavController {
                        nav.selectCategory()
                        
                        DispatchQueue.main.after(0.25) {
                            let conv: JMSGConversation = conversation as! JMSGConversation
                            nav.pushViewController(JCChatViewController(conversation: conv), animated: true)
                        }
                        
                        DispatchQueue.main.after(1, execute: {
                            weakSelf.navigationController?.popToRootViewController(animated: false)
                        })
                    }
                }
            }
        }
    }
    
    private func giftController(didClickExchangeButton sender: UIButton) {
        let xibView = ExchangeDiamonAlertView.init(frame: CGRect(x:0, y:0, width:ScreenWidth, height:ScreenHeight))
        xibView.exchangeItems = self.exchangeArr
        xibView.delegate = self
        self.view.addSubview(xibView)
        
    }
    
    private func giftController(didClickWithdrawButton sender: UIButton) {
        navigationController?.pushViewController(MTWithdrawController(), animated: true)
    }
}

extension MTGiftController: UITableViewDataSource, UITableViewDelegate {
    
    //MARK: UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: AccountListCell.reuseIdentity(), for: indexPath) as! AccountListCell
        cell.titleStr = indexPath.row == 0 ? "我收到的礼物" : "我收到的红包"
        cell.selectionStyle = .none
        if moneyArr.count > indexPath.row {
            cell.valueStr = "\(moneyArr[indexPath.row])"
        }
        return cell
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            let vc = MTGiftListController()
            vc.isSend = false
            navigationController?.pushViewController(vc, animated: true)
            
        } else {
            let vc = MTRedPacketListController()
            vc.isSend = false
            navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 170
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return headerView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}

extension MTGiftController: ExchangeDiamonAlertViewDelegate {
    func selectCell(_ model: MineWithdrawModel) {
        if model.money > self.model?.money ?? 0 {
            AlertManager.presentAlertView(message: "礼券余额不足")
            return
        }
        translateDiamond(model: model)
    }
    
    private func translateDiamond(model: MineWithdrawModel) {
        user_provider.originRequest(.translateDiamond(model.ticketAmount), callbackQueue: nil, progress: nil) { [weak self] (result, isCache) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let data = try? response.mapJSON() as? [String: Any], let code = data["code"] as? Int {
                    if code == 200 {
                        AlertManager.presentAlertView(message: "兑换成功")
                        weakself.queryReceiveStatics()
                    } else if let msg = data["message"] as? String {
                        AlertManager.presentAlertView(message: msg)
                    } else {
                        AlertManager.presentAlertView(message: "兑换失败")
                    }
                } else {
                    AlertManager.presentAlertView(message: "兑换失败")
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }
    }
}
